import { ref, onMounted } from 'vue';
import hljs from 'highlight.js';
import javascript from 'highlight.js/lib/languages/javascript';
import typescript from 'highlight.js/lib/languages/typescript';
import python from 'highlight.js/lib/languages/python';
import java from 'highlight.js/lib/languages/java';
import cpp from 'highlight.js/lib/languages/cpp';
import css from 'highlight.js/lib/languages/css';
import xml from 'highlight.js/lib/languages/xml';
import json from 'highlight.js/lib/languages/json';
import bash from 'highlight.js/lib/languages/bash';
import sql from 'highlight.js/lib/languages/sql';
import php from 'highlight.js/lib/languages/php';
import go from 'highlight.js/lib/languages/go';
import rust from 'highlight.js/lib/languages/rust';

// 注册常用语言
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('typescript', typescript);
hljs.registerLanguage('python', python);
hljs.registerLanguage('java', java);
hljs.registerLanguage('cpp', cpp);
hljs.registerLanguage('css', css);
hljs.registerLanguage('html', xml);
hljs.registerLanguage('json', json);
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('sql', sql);
hljs.registerLanguage('php', php);
hljs.registerLanguage('go', go);
hljs.registerLanguage('rust', rust);
hljs.registerLanguage('vue', xml);

export function useHighlight() {
  const isInitialized = ref(false);

  onMounted(() => {
    if (!isInitialized.value) {
      isInitialized.value = true;
    }
  });

  const highlightElement = (el: HTMLElement) => {
    if (!el) return;
    const blocks = el.querySelectorAll('pre code');
    blocks.forEach((block) => {
      const codeEl = block as HTMLElement;
      // 避免重复高亮
      if (codeEl.classList.contains('hljs')) {
        return;
      }
      try {
        hljs.highlightElement(codeEl);
      } catch (e) {
        console.warn('Failed to highlight code block:', e);
      }
    });
  };

  const highlightCode = (code: string, language: string) => {
    if (!code) return '';
    
    // 语言别名映射
    const languageMap: Record<string, string> = {
      'js': 'javascript',
      'ts': 'typescript',
      'py': 'python',
      'c++': 'cpp',
      'c#': 'csharp',
      'sh': 'bash',
      'shell': 'bash',
      'vue': 'html',
      'jsx': 'javascript',
      'tsx': 'typescript'
    };
    
    const normalizedLang = languageMap[language?.toLowerCase()] || language?.toLowerCase();
    
    if (normalizedLang && hljs.getLanguage(normalizedLang)) {
      try {
        return hljs.highlight(code, { language: normalizedLang }).value;
      } catch (e) {
        console.warn('Error highlighting code with language', normalizedLang, ':', e);
      }
    }
    
    // 自动检测语言
    try {
      const result = hljs.highlightAuto(code);
      return result.value;
    } catch (e) {
      console.warn('Error auto-highlighting code:', e);
      return code; // 返回原始代码
    }
  };

  return {
    highlightElement,
    highlightCode,
    isInitialized
  };
}